import hashlib
import base64
from datetime import datetime, timezone
from sqlalchemy.orm import Session
from app.tools_url_shorten.models import ToolsShortenedUrl


def create_short_link(db: Session, original_url: str):
    timestamp = datetime.now().replace(tzinfo=timezone.utc).timestamp()
    to_encode = f'{original_url}{timestamp}'

    short_link = base64.urlsafe_b64encode(hashlib.sha256(to_encode.encode()).digest()).decode()

    ToolsShortenedUrl.save(db, {'original_url': original_url, 'short_link': short_link})
    return short_link




if __name__ == '__main__':
    from datetime import datetime, timezone

    # timestamp = datetime.now().replace(tzinfo=timezone.utc).timestamp()
    # print(create_short_link("https://kibana.wolaidai.com/app/kibana#/discover?_g=(refreshInterval:(pause:!t,value:0),time:(from:'2022-03-29T08:46:19,000Z',mode:absolute,to:'2022-03-29T08:47:19,000Z'))&_a=(columns:!(message),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'fdcf5d60-a9f4-11e8-809c-57280b4ac664',key:level,negate:!f,params:(query:error,type:phrase),type:phrase,value:error),query:(match:(level:(query:error,type:phrase)))),('$state':(store:appState),meta:(alias:!n,disabled:!f,index:fdcf5d60-a9f4-11e8-809c-57280b4ac664,key:fields.app,negate:!f,params:(query:message-push-job,type:phrase),type:phrase,value:message-push-job),query:(match:(fields.app:(query:message-push-job,type:phrase))))),index:fdcf5d60-a9f4-11e8-809c-57280b4ac664,interval:auto,query:(language:lucene,query:''),sort:!('@timestamp',desc)", timestamp))
